<?

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

init_session();




include($_SERVER['DOCUMENT_ROOT'].'/portals/header.inc.php');


#########################
# Setup Defaults


$sql = array();
$sql['columns'] = 'portal.title,domain,label AS name,COUNT(*) AS count';
$sql['tables'] = array();

$sql['tables'][] = "portal";
$sql['tables'][] = "INNER JOIN gridimage_group AS gg USING (portal_id)";


$sql['wheres'] = array();
$sql['wheres'][] = "public = 'Y'";
$sql['wheres'][] = "label != '(Other)'";


$sql['group'] = "portal_id,label";
$sql['order'] = "label";

$sql['limit'] = 100;


#########################
# Possiblities and defaults

$view = 'text';
$by = 'cluster2';
$bytitle = "Year Taken";
$filter = 'taken';
$pgsize = $sql['limit'];
$order = 'name';
$filter = "cluster2";

$views = array(
'text' => '&middot; Text Listing',
'cloud' => '&middot; Word Cloud',
);

$bys = array('cluster2'=>'Automatic Cluster2');

$orders = array(
'name' => 'Name/Title',
'count' => 'Count'
);

#########################
# Customise





if (!empty($_GET['order'])) {
	if (!empty($_GET['in']) && strlen($_GET['in']) == 1) $in = $_GET['in'];
	$asc = ($in == 'a')?'asc':'desc';
	switch ($_GET['order']) {
		case 'count': $sql['order'] = "`count` $asc"; $order = 'count';break;
		case 'group': 
		     default:  
			if ($_GET['by'] == 'realname') {
				$sql['order'] = "`realname` $asc";
			} elseif ($asc == 'desc') {
				$sql['group'] .= " $asc";
			} 
			$order = 'label'; break;
	}
	$title = '';
}
if ($sql['order'] == '`count` desc') {
	$views['wordle'] = '&middot; Wordle Maker';
}

if (!empty($_GET['view'])) {
	
	if (isset($views[$_GET['view']])) {
		$view = $_GET['view'];
	}
} 

#########################
# html form

print "<form class=\"sform\">";

print "<div class=\"d\">";
print "View style<br/>";
print "<select name=\"view\" onchange=\"this.form.submit()\">";
foreach ($views as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$view)?' selected':'',$value);
}
print "</select></div>";

print "<div class=\"d\">";
print "Order<br/>";
print "<select name=\"order\" onchange=\"this.form.submit()\">";
foreach ($orders as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$order)?' selected':'',$value);
}
print "</select>";
print "<select name=\"in\" onchange=\"this.form.submit()\">";
$ins = array('a'=>'Asc','d'=>'Desc');
foreach ($ins as $key => $value) {
	printf("<option value=\"%s\"%s>%s</option>",$key,($key==$in)?' selected':'',$value);
}
print "</select></div>";

if ($_GET['resort'])
	print "<input type=hidden name=resort value=1 />";

print "</form>";

#########################
# paging

if (!empty($_GET['page'])) {
				
	$page = intval($_GET['page']);

	if (empty($page) || $page < 1) {$page = 1;}
	#if ($page > $numberOfPages) {$page = $numberOfPages;}

	$pg = ($page -1)* $pgsize;

	$sql['limit'] = "$pg,$pgsize";
} else {
	$page = 1;
	$pg = 0;
}

#########################
# Display results!
if ($_GET['qq']) 
	print_rp($sql);
	

$query = sqlMakeQuery($sql);
if ($_GET['qq']) 
	print_rp($query);
	

if ($_GET['resort'] && $view == 'cloud')
	$query = "SELECT * FROM ($query) t1 ORDER BY name";

$result = queryExecute($query);

if ($result) {
	print "<h3>Breakdown by Cluster2 from all <a href=\"portals.php\">Public Portals</a></h3>";
	
	
	
	if ($view == 'wordle') {
		
		?>
		<form action="http://www.wordle.net/compose" method="post" name="theForm"> 
		<input type=text name=wordcounts value="<? 
		while($c = mysql_fetch_assoc($result)) {
			print he($c['name']).":{$c['count']},";
		}
		?>"> 
		<input type=submit value="Continue to wordle.net &gt;&gt;"> 
		</form>
		<?
		
		
	} elseif ($view == 'cloud') {
		
		$mult = ($by == 'cluster2')?0.2:0.6;
		
		print "<div class=\"cloud\">";
		while($c = mysql_fetch_assoc($result)) {
			if (empty($c['value'])) {
				$c['value'] = $c['name'];
			}
			$link = linktoself(array($filter=>$c['value'],'delete'=>array('by','order','in')),"http://{$c['domain']}.portal.geographs.org/"); 
			$size = sprintf("%.1f",log($c['count']*30))*$mult;
			echo "&middot;<a href=\"$link\" style=\"font-size:{$size}em\" title=\"{$c['count']} image(s) in ".he($c['title'])."\">".he($c['name'])."</a>&middot; ";

		}
		print "</div>";
		
	} else {
		print "<table class=\"report\">";
		print "<tr>";
		print "<th>{$bys[$by]}</th>";
		print "<th>Count</th>";
		print "</tr>";

		while($c = mysql_fetch_assoc($result)) {
			if (empty($c['value'])) {
				$c['value'] = $c['name'];
			}
			print "<tr>";
			$link = linktoself(array($filter=>$c['value'],'delete'=>array('by','order','in')),"http://{$c['domain']}.portal.geographs.org/"); 
			print "<td><a href=\"$link\" title=\"Portal: ".he($c['title'])."\">".he($c['name'])."</a></td>";

			print "<td align=right>{$c['count']}</td>";

			print "</tr>";

		}
		print "</table>";
	}
	
	if (mysql_num_rows($result) == $pgsize || isset($_GET['page'])) {
		$count_query = sqlMakeCountQuery($sql);

		$resultCount = getOne($count_query);

		#if ($resultCount > mysql_num_rows($result)) {
		#	print "Showing $pgsize of $resultCount rows";
		#}

		$numberOfPages = ceil($resultCount/$pgsize);

		if ($numberOfPages > 1) {
			print "<p class='pages'>Page $page of $numberOfPages. ";
			printf("Row %d..%d of %d. ",($pg)+1,min(($pg)+$pgsize,$resultCount),$resultCount);
			print pagesString($page,$numberOfPages)."</p>";
		}

	}
	
	
	if ($filtered) {
		print "<p align=center><a href=\"".linktoself(array('view'=>'thumbs','delete'=>array('by','order','in')),'/')."\">View these images</a></p>";
	}
	
	switch ($by) {
		case 'cluster': print "<p>The <b>Cluster label</b> shown here is an automatically extracted label for a photo. The analysis (by the <a href=\"http://project.carrot2.org/\">Carrot2</a> software) is done on a grid square basis on the main Geograph site.</p>"; break;
		case 'cluster2': print "<p>The <b>Cluster2 label</b> shown here is an automatically extracted label for a photo. The analysis (by the <a href=\"http://project.carrot2.org/\">Carrot2</a> software) is done directly in this portal, so tends to work well on the highly specific images (usually better than 'cluster').</p>"; break;
		case 'term': print "<p>The <b>Term</b> shown here is an automatically extracted label for a photo. The extraction is done with the <a href=\"http://developer.yahoo.com/search/content/V1/termExtraction.html\">Yahoo Term Extraction API</a>. NOTE: only images upto id 1458144 have been analyised.</p>"; break;
	}	
	
	
	
} else {
	print "<p>No Images to show at this time.</p>";
}

include($_SERVER['DOCUMENT_ROOT'].'/portals/footer.inc.php');


#########

